<?php

namespace App\Services;

use Illuminate\Support\Facades\Log;
use Spatie\Activitylog\Models\Activity;
use Spatie\Activitylog\ActivityLogger;

class LogService
{
    protected $activityLogger;

    public function __construct(ActivityLogger $activityLogger)
    {
        $this->activityLogger = $activityLogger;
    }

    /**
     * 记录用户活动
     */
    public function logUserActivity(string $description, $subject = null, array $properties = []): Activity
    {
        return $this->activityLogger
            ->performedOn($subject)
            ->withProperties($properties)
            ->log($description);
    }

    /**
     * 记录房间活动
     */
    public function logRoomActivity(string $description, $room, array $properties = []): Activity
    {
        return $this->logUserActivity($description, $room, $properties);
    }

    /**
     * 记录订单活动
     */
    public function logOrderActivity(string $description, $order, array $properties = []): Activity
    {
        return $this->logUserActivity($description, $order, $properties);
    }

    /**
     * 记录API请求
     */
    public function logApiRequest(string $method, string $url, array $data = [], int $statusCode = 200, float $responseTime = 0): void
    {
        Log::channel('api')->info('API Request', [
            'method' => $method,
            'url' => $url,
            'data' => $data,
            'status_code' => $statusCode,
            'response_time' => $responseTime,
            'timestamp' => now()->toISOString(),
        ]);
    }

    /**
     * 记录API错误
     */
    public function logApiError(string $method, string $url, \Exception $exception, array $data = []): void
    {
        Log::channel('api')->error('API Error', [
            'method' => $method,
            'url' => $url,
            'data' => $data,
            'error' => $exception->getMessage(),
            'trace' => $exception->getTraceAsString(),
            'timestamp' => now()->toISOString(),
        ]);
    }

    /**
     * 记录业务操作
     */
    public function logBusinessOperation(string $operation, array $context = []): void
    {
        Log::channel('business')->info($operation, array_merge($context, [
            'timestamp' => now()->toISOString(),
        ]));
    }

    /**
     * 记录性能指标
     */
    public function logPerformance(string $operation, float $duration, array $metrics = []): void
    {
        Log::channel('performance')->info('Performance Metric', [
            'operation' => $operation,
            'duration' => $duration,
            'metrics' => $metrics,
            'timestamp' => now()->toISOString(),
        ]);
    }

    /**
     * 记录缓存操作
     */
    public function logCacheOperation(string $operation, string $key, bool $success = true, array $context = []): void
    {
        Log::channel('cache')->info('Cache Operation', [
            'operation' => $operation,
            'key' => $key,
            'success' => $success,
            'context' => $context,
            'timestamp' => now()->toISOString(),
        ]);
    }

    /**
     * 记录数据库查询
     */
    public function logDatabaseQuery(string $query, float $duration, array $bindings = []): void
    {
        Log::channel('database')->info('Database Query', [
            'query' => $query,
            'duration' => $duration,
            'bindings' => $bindings,
            'timestamp' => now()->toISOString(),
        ]);
    }

    /**
     * 记录安全事件
     */
    public function logSecurityEvent(string $event, array $context = []): void
    {
        Log::channel('security')->warning('Security Event', array_merge($context, [
            'event' => $event,
            'timestamp' => now()->toISOString(),
        ]));
    }

    /**
     * 记录系统事件
     */
    public function logSystemEvent(string $event, array $context = []): void
    {
        Log::channel('system')->info('System Event', array_merge($context, [
            'event' => $event,
            'timestamp' => now()->toISOString(),
        ]));
    }

    /**
     * 获取活动日志
     */
    public function getActivityLogs($subject = null, int $limit = 50): \Illuminate\Database\Eloquent\Collection
    {
        $query = Activity::latest();
        
        if ($subject) {
            $query->where('subject_type', get_class($subject))
                  ->where('subject_id', $subject->id);
        }
        
        return $query->limit($limit)->get();
    }

    /**
     * 清理旧日志
     */
    public function cleanOldLogs(int $days = 30): int
    {
        $cutoffDate = now()->subDays($days);
        
        return Activity::where('created_at', '<', $cutoffDate)->delete();
    }

    /**
     * 获取日志统计
     */
    public function getLogStats(): array
    {
        return [
            'total_activities' => Activity::count(),
            'today_activities' => Activity::whereDate('created_at', today())->count(),
            'this_week_activities' => Activity::whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()])->count(),
            'this_month_activities' => Activity::whereMonth('created_at', now()->month)->count(),
        ];
    }
}
